package com.lyy.yygh.msm.controller;

import com.lyy.yygh.common.result.Result;
import com.lyy.yygh.msm.service.MsmService;
import com.lyy.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendcode(@PathVariable String phone){
        //从redis获取验证码，如果获取到返回ok
        String s = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(s)){
            return Result.ok();
        }

        //获取不到，生成验证码整合短信服务进行发送
        s= RandomUtil.getFourBitRandom();
        boolean isSend = msmService.send2(phone, s);

        //生成验证码返回到redis中，设置有效时间
        if(isSend){
            redisTemplate.opsForValue().set(phone,s,2, TimeUnit.MINUTES);
            return Result.ok();
        }else{
            return Result.fail().message("发送短信失败");
        }

    }


}
